<template>
    <div class="home-container">
      <SideMenu />
      <!-- 主内容区 -->
      <div class="main-content"
         @touchstart="handleTouchStart"
         @touchmove="handleTouchMove"
         @touchend="handleTouchEnd">
        <!-- 顶部导航栏 -->
        <!-- <div class="header">
          <UserMenu />
        </div> -->
        <div class="nav-bar">
          <div class="nav-left">
            <h1 class="page-title">主题</h1>
            <div class="nav-items">
              <div v-for="(item, index) in navItems" 
                   :key="index" 
                   :class="['nav-item', { active: currentNav === item }]"
                   @click="currentNav = item">
                {{ item }}
              </div>
            </div>
          </div>
          <el-tooltip
            content="创建主题"
            placement="left"
            effect="dark">
            <div class="create-button" @click="handleCreate">
              <img src="@/assets/icon/more-icon.png" alt="创建" class="create-icon">
            </div>
          </el-tooltip>
        </div>
    
        <!-- 瀑布流内容区 -->
        <div class="content-grid">
          <div v-for="(item, index) in currentPageSubjects" 
               :key="index" 
               class="grid-item"
               @click="handleItemClick(item)">
            <div class="item-header">
              <div class="item-image">
                <el-avatar 
                  :size="40"
                  :style="{ 
                    backgroundColor: getAvatarColor(item.matter || ''),
                    width: '100%',
                    height: '100%',
                    fontSize: '24px'
                  }"
                  :fit="'cover'"
                >
                  <template v-if="item.avatar">
                    <img :src="item.avatar" :alt="item.matter">
                  </template>
                  <template v-else>
                    <span style="transform: scale(1); display: inline-block;">
                      {{ (item.matter || '').charAt(0).toUpperCase() }}
                    </span>
                  </template>
                </el-avatar>
              </div>
              <div class="matter-title">{{ item.matter }}</div>
            </div>
            <div class="item-description">{{ item.description }}</div>
            <div class="item-info">
              <div class="user-info">
                <el-avatar :size="24" :src="item.creator?.avatar"/>
                <span>{{ item.creator?.nickname }}</span>
              </div>
              <div class="interaction">
                <span>
                  <i class="i-ep-heart" />
                  {{ item.favorCount }}
                </span>
              </div>
            </div>
            <div class="action-buttons" v-if="canOperator(item)">
              <el-popover
                placement="bottom"
                :width="80"
                trigger="click"
                @show="handleMoreClick($event)"
              >
                <template #reference>
                  <img src="@/assets/icon/more2.png" class="more-icon" @click.stop>
                </template>
                <div class="action-menu">
                  <div class="action-item" @click.stop="handleEdit(item)">
                    <img src="@/assets/icon/edit.png" class="action-icon">
                    <span>编辑</span>
                  </div>
                  <div class="action-item" @click.stop="handleDelete(item)">
                    <img src="@/assets/icon/delete.png" class="action-icon">
                    <span>删除</span>
                  </div>
                </div>
              </el-popover>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted,computed,watch } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/user'
  import { ListSubjects, DeleteSubject } from '@/api/subject'
  import {ListSubjectsResponse, Subject} from '@/types/proto/api/v1/subject_service'
  import SideMenu from '@/components/SideMenu.vue'
  import UserMenu from '@/components/UserMenu.vue'

  const router = useRouter()
  const userStore = useUserStore()
  
  const navItems =[""]
  // const navItems = ['推荐', '穿搭', '美食', '彩妆', '影视', '职场', '情感', '家居', '游戏', '旅行', '健身']
  // const currentNav = ref('推荐')
  const currentNav = ref('')
  const isAdmin = computed(() => userStore.userInfo?.role === 'TENANT_ADMIN')
  const canOperator = (item: Subject) =>{
    if(isAdmin.value){
      return true
    }

    if(item.creator?.id === userStore.userInfo?.id){
      return true
    }

    return false
  }

  // const subjects = ref<SubjectItem[]>([])
  const subjects = ref<Subject[]>([])
  const totalPages = computed(() => Math.ceil(subjectsTotal.value / pageSize))

  const pageSize = 5 // 每页显示5个
  const currentPage = ref(1)
  const subjectsTotal = ref(0)
  const currentPageSubjects = computed(() => {
    return subjects.value
  })
  // 处理发现点击
  const handleDiscover = () => {
    const pageToken = { limit: pageSize, offset: 0 }
    const filter = `visibilities == ['TENANT']`
    ListSubjects({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListSubjectsResponse)=>{
      subjectsTotal.value = res.totalSize
      subjects.value=[]
      res.Subjects.map((subject) => (subjects.value.push(subject)))
    }).catch(error => {
        console.error('Failed to fetch news:', error)
    })
  }

const handleCreate = () => {
    router.push('/subject/config')
}
  
const touchStartY = ref(0)
const touchThreshold = 50  // 触发翻页的阈值

// 处理触摸开始
const handleTouchStart = (event: TouchEvent) => {
  touchStartY.value = event.touches[0].clientY
}

const handleMoreClick = (event: Event) => {
    event.stopPropagation()
}

const handleEdit = (item: Subject) => {
    router.push(`/subject/config?subject=${item.urn}`)
}

const handleDelete = (item: Subject) => {
    DeleteSubject({urn:item.urn}).then(() => {
      subjects.value = subjects.value.filter((subject) => subject.urn !== item.urn)
      ElMessage.success('删除成功')
      // 可以在这里刷新列表
    }).catch(() => {
      ElMessage.error('删除失败')
    })
}

// 处理触摸移动
const handleTouchMove = (event: TouchEvent) => {
  event.preventDefault() // 防止页面滚动
}

// 处理触摸结束
const handleTouchEnd = (event: TouchEvent) => {
  const touchEndY = event.changedTouches[0].clientY
  const deltaY = touchEndY - touchStartY.value
  console.log('touch delay:', deltaY, "currenct page:", currentPage.value)

  // 向上滑动，显示下一页
  if (deltaY < -touchThreshold && currentPage.value < totalPages.value) {
    console.log('向上滑动')
    handlePageChange(currentPage.value + 1)
  }
  // 向下滑动，显示上一页
  else if (deltaY > touchThreshold && currentPage.value > 1) {
    console.log('向下滑动')
    handlePageChange(currentPage.value - 1)
  }
}

const showPageHint = () => {
  ElMessage({
    message: currentPage.value === totalPages.value ? '已经是最后一页' : '已经是第一页',
    type: 'info',
    duration: 1500
  })
}


const handlePageChange = (page: number) => {

    if (page < 1 || page > totalPages.value) {
      showPageHint()
      return
    }

    console.log("click page:", page)
    currentPage.value = page

    const pageToken = { limit: pageSize, offset: (page - 1) * pageSize }
    HandleVisibilityPageChange(pageToken)
  }

const HandleVisibilityPageChange = (pageToken: any) => {    // const pageToken = { limit: pageSize, offset: (page - 1) * pageSize }
    const filter = `visibilities == ['TENANT']`
    ListSubjects({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListSubjectsResponse)=>{
      subjectsTotal.value = res.totalSize
      subjects.value=[]
      res.Subjects.map((subject) => (subjects.value.push(subject)))
    }).catch(error => {
        console.error('Failed to fetch news:', error)
    })
  }
  
  // Add onMounted hook to check token
  onMounted(() => {
    if (!userStore.token) {
      router.push('/signin')
    }
    handleDiscover()
  })

  // 处理项目点击
  const handleItemClick = (item: Subject) => {
    console.log("handleItemClick:", item)
    // 检查用户是否登录
    if (!userStore.token) {
      ElMessage.warning('请先登录')
      router.push('/signin')
      return
    }

    userStore.subject = item
    router.push({
      path: '/say',
      children: {
        
      },
      query: {
        subject: item.urn
      }
    })
  }

const getAvatarColor = (name: string) => {
  // 预定义一组好看的颜色
  const colors = [
    '#f56a00', '#7265e6', '#ffbf00', '#00a2ae',
    '#1890ff', '#52c41a', '#722ed1', '#eb2f96',
    '#faad14', '#13c2c2', '#fa541c', '#2f54eb'
  ];
  
  // 使用名称生成一个固定的数字
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  // 使用这个数字来选择颜色
  return colors[Math.abs(hash) % colors.length];
}
  </script>
  
  <style scoped lang="scss">
  .home-container {
    display: flex;
    max-width: 1440px;
    margin: 0 auto;
    padding: 0;
  }
  
  .main-content {
    flex: 1;
    margin-left: 100px;
    padding: 20px 40px;
  }
  
  .header {
    display: flex;
    justify-content: flex-end;
    padding: 8px 16px;
    border-bottom: 1px solid #eee;
  }
  
  .nav-bar {
    position: sticky;
    top: 0;
    background: white;
    padding: 10px 0;
    z-index: 100;
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .nav-left {
      display: flex;
      align-items: center;
      gap: 24px;
    }

    .create-button {
      cursor: pointer;
      padding: 8px;
      border-radius: 4px;
      transition: background-color 0.2s;
  
      &:hover {
        background-color: #f5f5f5;
      }
  
      .create-icon {
        width: 24px;
        height: 24px;
      }
    }
  
    .nav-items {
      display: flex;
      gap: 24px;
      overflow-x: auto;
      padding: 0;
  
      .nav-item {
        cursor: pointer;
        white-space: nowrap;
        color: #666;
        
        &.active {
          color: #333;
          font-weight: bold;
        }
  
        &:hover {
          color: #333;
        }
      }
    }
  }
  
  .content-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 12px;
    padding: 0;
    justify-items: start;
  }
  
  .grid-item {
    width: 100%;
    max-width: 200px;
    border-radius: 6px;
    overflow: hidden;
    background: white;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    transition: transform 0.2s;
    cursor: pointer;
    position: relative;
    display: flex;
    flex-direction: column;
    min-height: 200px;
  
    &:hover {
      transform: translateY(-2px);
      
      .action-buttons {
        opacity: 1;
      }
    }
  
    .item-header {
      display: flex;
      align-items: center;
      padding: 12px;
      gap: 12px;

      .item-image {
        flex-shrink: 0;
        width: 40px;
        height: 40px;
      }

      .matter-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  
    .item-description {
      padding: 0 12px;
      margin: 8px 0;
      font-size: 14px;
      color: #666;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 5;
      line-clamp: 5; 
      -webkit-box-orient: vertical;
      line-height: 1.4;
      flex: 1;
      min-height: 40px;
      word-wrap: break-word;
      word-break: break-all;
    }
  
    .item-info {
      margin-top: auto;
      display: flex;
      align-items: center;
      padding: 8px;
      text-align: left;
  
      h3 {
        margin: 0 0 4px;
        font-size: 13px;
        line-height: 1.3;
        display: -webkit-box;
        -webkit-line-clamp: 5;
        line-clamp: 5; 
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
  
      .user-info {
        display: flex;
        align-items: center;
        gap: 4px;
        margin-bottom: 4px;
        
        span {
          font-size: 13px;
          color: #666;
        }

        .el-avatar {
          width: 20px;
          height: 20px;
        }
      }
  
      .interaction {
        font-size: 11px;
        color: #999;
  
        i {
          margin-right: 3px;
        }
      }
    }

    .action-buttons {
      position: absolute;
      right: 8px;
      bottom: 8px;
      opacity: 0;
      transition: opacity 0.2s;
      z-index: 2;

      .more-icon {
        width: 20px;
        height: 20px;
        cursor: pointer;
      }
    }
  }
  
  .action-menu {
    .action-item {
      display: flex;
      align-items: center;
      padding: 8px;
      cursor: pointer;
      
      &:hover {
        background-color: #f5f5f5;
      }

      .action-icon {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }

      span {
        font-size: 12px;
        color: #333;
      }
    }
  }
  
  @media screen and (max-width: 1440px) {
    .home-container {
      max-width: 100%;
    }
    
    .main-content {
      margin-left: 220px;
    }
    
    .content-grid {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }
    .grid-item {
      max-width: 180px;
    }
  }
  
  @media screen and (max-width: 1200px) {
    .main-content {
      margin-left: 200px;
    }
    
    .content-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    }
    .grid-item {
      max-width: 160px;
    }
  }
  </style>